/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package business;

import domain.*;
import persistence.RegistrationPersistence;

/**
 *
 * @author admin
 */
public class RegistrationBusiness {
/**
     * Registers a new user to the system
     * @param user A user object with the users details
     * @return A RegistrationError object containing the details of the occurred error
     */
    public RegistrationError register(User user) {
        RegistrationError error = new RegistrationError();
        if (validateUser(user)) {
            RegistrationPersistence registration = new RegistrationPersistence();
            if (validateUsername(registration.validateUsername(user.getUsername()))) {

                if (!registration.addNewUser(user)) {
                    error.setDbError(true);
                    error.setMessage("Error while accessing the database");
                }
            } else {
                error.setUnameExists(true);
                error.setMessage("Username already exists");
            }
        } else {
            error.setValidationError(true);
            error.setMessage("Please fill all the fields");
        }
        return error;
    }
/**
     * validates the user input
     * @param user A user object that contains the details entered by the user
     * @return true if the input is valid
     */
    private boolean validateUser(User user) {
        int errorCount = 0;

        if (user.getFirstName().length() == 0) {
            errorCount++;
        }
        if (user.getLastName().length() == 0) {
            errorCount++;
        }
        if (user.getEmail().length() == 0) {
            errorCount++;
        }
        if (user.getUsername().length() == 0) {
            errorCount++;
        }
        if (user.getPassword().length() == 0) {
            errorCount++;
        }

        if (errorCount == 0) {
            return true;
        } else {
            return false;
        }
    }
/**
     * 
     * @param usernameCount the number of occurrences of a given username in the database
     * @return true if a username is unique
     */
    private boolean validateUsername(int usernameCount) {
        boolean returnStatus = false;
        if (usernameCount != 0) {
            returnStatus = false;
        } else {
            returnStatus = true;
        }
        return returnStatus;
    }
}
